﻿#include <iostream>
#include <stdlib.h>
#include <string>
#include <winsock2.h>
void ErrorHandle(const char *message);
#define BUF_SIZE 1024
int main(int args, char *argv[])
{
  WSADATA wsadata;                      // 初始化操作的信息（output）
  WSAStartup(MAKEWORD(2, 2), &wsadata); // 初始化Winsock库；
  // step01:创建套接字
  SOCKET sock_clnt;
  sock_clnt = socket(PF_INET, SOCK_STREAM, 0);
  if (sock_clnt == INVALID_SOCKET)
    ErrorHandle("socket() error!");
  // step02:请求连接
  SOCKADDR_IN addr_serv;
  memset(&addr_serv, 0, sizeof(addr_serv));
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.S_un.S_addr = inet_addr(argv[1]);
  addr_serv.sin_port = htons(atoi(argv[2]));
  auto connect_result = connect(sock_clnt, (SOCKADDR *)&addr_serv, sizeof(addr_serv));
  if (connect_result == -1)
    ErrorHandle("connect() error!");
  else
    std::cout << "Conneected..." << std::endl;

  char message[BUF_SIZE];

  while (1)
  {
    std::cout << "Input message(Q to quit):" << std::endl;
    fgets(message, BUF_SIZE, stdin);
    if (strcmp(message, "q\n") == 0 || strcmp(message, "Q\n") == 0)
      break;
    send(sock_clnt, message, strlen(message), 0);
    auto strlen = recv(sock_clnt, message, BUF_SIZE - 1, 0);
    std::cout << "Message from server:" << message << std::endl;
  }
  WSACleanup();
  closesocket(sock_clnt);
  return 0;
}
void ErrorHandle(const char *message)
{
  std::cout << message << std::endl;
  exit(-1);
}